import { BaseReactElementState, BaseReactElement, reactControl, BaseReactElementControl } from "pao-aop-client";
import React from "react";
import { addon } from "pao-aop";
import { WhiteSpace, List, Picker, Radio, InputItem, Button, WingBlank, Toast } from "antd-mobile";
import { AppServiceUtility } from "src/projects/app/appService";
import { request } from "src/business/util_tool";
import { ROUTE_PATH } from "src/projects/app/util-tool";
const RadioItem = Radio.RadioItem;
/**
 * 组件：能力评估创建/详情状态
 */
export interface ChangeCompetenceAssessmentViewState extends BaseReactElementState {
    // 是否已经发送
    isSend: boolean;
    // 选择的人名
    select_person_value?: any;
    // 选择的人数组
    select_person: [];
    // 选择的模板名称
    select_template_value?: any;
    // 选择的模板数组
    select_template: [];
    // 选择的模板数据
    select_template_item: any;
    // 单选的数据
    project_list?: any;
    // 总分
    total?: string | number;
    // id
    id?: string | undefined;
    // 评估时间
    create_date?: any;
}

/**
 * 组件：能力评估创建/详情
 * 任务详情
 */
export class ChangeCompetenceAssessmentView extends BaseReactElement<ChangeCompetenceAssessmentViewControl, ChangeCompetenceAssessmentViewState> {
    constructor(props: any) {
        super(props);
        this.state = {
            select_person: [],
            // 注释2：[]代表这是正常数据，如果是false代表数据紊乱，user为空
            select_person_value: [],
            select_template: [],
            // 注释1：[]代表这是正常数据，如果是false代表数据紊乱，template为空但是有project_list数据，所以需要用新数据替换掉个人数据
            select_template_value: [],
            select_template_item: false,
            isSend: false,
            total: '0',
            project_list: [],
            // 当前id
            id: this.props.match!.params.key || undefined,
        };
    }
    componentDidMount() {
        // 获取单条数据
        if (this.state.id) {
            request(this, AppServiceUtility.competence_assessment_service.get_competence_assessment_list!({ 'id': this.state.id }, 1, 1))
                .then((datas: any) => {
                    // 暂存
                    let dataObj = datas.result[0],
                        template_id: boolean | any[] = false,
                        user_id: boolean | any[] = false;
                    // 注释1
                    if (dataObj['template'][0]) {
                        this.changeTemplate([dataObj['template'][0]['id']]);
                        template_id = [dataObj['template'][0]['id']];
                    }
                    // 注释2
                    if (dataObj['user'][0]) {
                        user_id = [dataObj['user'][0]['id']];
                    }
                    this.setState({
                        select_person_value: user_id,
                        select_template_value: template_id,
                        project_list: dataObj.project_list,
                        total: this.getTotal(dataObj.project_list),
                        create_date: dataObj.create_date || undefined,
                    });
                });
        }
        // 获取人员数据
        request(this, AppServiceUtility.person_org_manage_service.get_personnel_elder!({}))
            .then((datas: any) => {
                this.setState({
                    select_person: datas.result,
                });
            });
        // 获取模板数据
        request(this, AppServiceUtility.assessment_template_service.get_assessment_template_list!({}))
            .then((datas: any) => {
                this.setState({
                    select_template: datas.result,
                });
            });
    }
    // 变更人员的名字
    changePerson = (e: any) => {
        this.setState({
            select_person_value: e,
        });
    }
    // 变更模板的名字
    changeTemplate = (e: any) => {
        let select_template_value = this.state.select_template_value;
        if (select_template_value !== e) {
            this.setState({
                select_template_value: e,
            });
            // 获取模板数据
            request(this, AppServiceUtility.assessment_template_service.get_assessment_template_list!({ 'id': e[0] }, 1, 10))
                .then((datas: any) => {
                    // 注释1
                    if (select_template_value === false) {
                        this.setState({
                            project_list: datas.result,
                            select_template_item: datas.result,
                            total: 0,
                        });
                    } else {
                        this.setState({
                            select_template_item: datas.result,
                        });
                    }
                });
        }
    }
    save = () => {
        let state = this.state;
        let params = {
            id: state.id,
            elder: state.select_person_value[0],
            template: state.select_template_value[0],
            total_score: state.total,
            project_list: state.project_list,
        };
        Toast.loading('Loading...', 11, () => {
        });
        let st = setTimeout(
            () => {
                Toast.hide();
                Toast.fail('操作失败，请稍候再试', 3);
            },
            10000
        );
        // 发送更新请求
        request(this, AppServiceUtility.competence_assessment_service.update_competence_assessment!(params))
            .then((data: any) => {
                if (data === 'Success') {
                    clearTimeout(st);
                    Toast.hide();
                    Toast.success('操作成功', 3);
                    setTimeout(
                        () => {
                            this.props.history!.push(ROUTE_PATH.competenceAssessment);
                        },
                        3000
                    );
                } else {
                    Toast.fail('操作失败，请稍候再试', 3);
                }
            });
        return;
    }
    // 计算总分
    getTotal(lists: any) {
        console.log(lists);
        let total: number = 0;
        for (let i in lists) {
            if (lists[i] && lists[i].ass_info.value) {
                total += Number(lists[i].ass_info.value);
            }
        }
        return total.toString();
    }
    onChange = (value: any, listIndex: number) => {
        let project_list = this.state.project_list;
        project_list[listIndex].ass_info.value = value;
        this.setState({
            total: this.getTotal(project_list),
            project_list,
        });
    }
    render() {
        const
            borderBoth = {
                borderTop: '1px solid #ddd',
                borderBottom: '1px solid #ddd',
            };

        let person = this.state.select_person;
        let select_person: any[] = [];
        person!.map((item: any) => {
            select_person.push({
                label: item.name,
                value: item.id,
            });
        });
        let template = this.state.select_template;
        let select_template: any[] = [];
        template!.map((item: any) => {
            select_template.push({
                label: item.template_name,
                value: item.id,
            });
        });
        return (
            <div>
                <WhiteSpace size="xl" />
                <List>
                    <Picker data={select_person} cols={1} value={this.state.select_person_value} onChange={(e) => this.changePerson(e)}>
                        <List.Item arrow="horizontal" style={borderBoth}>选择长者</List.Item>
                    </Picker>
                </List>
                <WhiteSpace size="sm" />
                <List>
                    <Picker data={select_template} cols={1} value={this.state.select_template_value} onChange={(e) => this.changeTemplate(e)}>
                        <List.Item arrow="horizontal" style={borderBoth}>选择模板</List.Item>
                    </Picker>
                </List>
                {(() => {
                    if (this.state.select_template_item !== false) {
                        let list: any = [];
                        this.state.select_template_item!.map((item: any, listIndex: number) => {
                            let child: any = [];
                            item.ass_info.dataSource.map((i: any, index: number) => {
                                child.push(<RadioItem key={`radio-${listIndex}${index}`} checked={this.state.project_list[listIndex].ass_info.value === i.score} onChange={() => this.onChange(i.score, listIndex)}>{i.option_content}（{i.score}分）</RadioItem>);
                            });
                            list.push(<div key={`list-${listIndex}`}>
                                <List renderHeader={() => { return item.ass_info.project_name; }}>
                                    {child}
                                </List>
                            </div>);
                        });
                        return <div>
                            <WhiteSpace size="xs" />
                            {list}
                            <WhiteSpace size="xl" />
                            <WhiteSpace size="xl" />
                            <List>
                                <InputItem value={`${this.state.total} 分`} editable={false}>总得分</InputItem>
                            </List>
                        </div>;
                    }
                    // return <div style={{ minHeight: '200px' }} />;
                    return null;
                })()}
                {(() => {
                    if (this.state.id && this.state.create_date) {
                        return <div>
                            <WhiteSpace size="sm" />
                            <List>
                                <InputItem value={`${this.state.create_date}`} editable={false}>评估时间</InputItem>
                            </List>
                        </div>;
                    }
                    return null;
                })()}
                <WhiteSpace size="xl" />
                <WhiteSpace size="xl" />
                <WingBlank size="lg">
                    <Button type="primary" onClick={this.save}>保存</Button>
                </WingBlank>
                <WhiteSpace size="xl" />
                <WhiteSpace size="xl" />
            </div >
        );
    }
}

/**
 * 控件：能力评估创建/详情控制器
 * 任务详情
 */
@addon('ChangeCompetenceAssessmentView', '能力评估创建/详情', '任务详情')
@reactControl(ChangeCompetenceAssessmentView, true)
export class ChangeCompetenceAssessmentViewControl extends BaseReactElementControl {

}